package com.zl.csMall.code;

import com.zl.csMall.mine.user.po.User;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: 登录缓存
 * @author: ChenNing
 * @date 2025-10-15 11:05
 */
@Component
public class LoginCacheMap {

    private final ConcurrentHashMap<String, Object> userSessionCache = new ConcurrentHashMap<>();


    public void addUser(String token, User user){
        userSessionCache.put(token, user);
    }

    public User getUser(String token){
        return (User) userSessionCache.get(token);
    }

    public void removeUser(String token){
        userSessionCache.remove(token);
    }

    public Set<String> getAllKeys() {
        return userSessionCache.keySet();
    }

    public void extrusion(String openId) {
        for (String token : userSessionCache.keySet()) {
            User user = (User) userSessionCache.get(token);
            if (openId.equals(user.getOpenId())) {
                // 该用户已登录，强迫下线
                userSessionCache.remove(token);
                return;
            }
        }
    }

}
